const fs = require('fs');
const Cesium = require('cesium');

let filename = 'indoor_3d.geojson';
let outputfilename = 'indoor_3d_cy.json';

let geojsonStr = fs.readFileSync(filename);
let indoor_3d_geojson = JSON.parse(geojsonStr);

let features = indoor_3d_geojson.features;

let cyelements = [];
let vertices = {};
let vertexid = 0;
features.forEach((feature)=>{
	let len = feature.geometry.coordinates.length;
	let start = feature.geometry.coordinates[0];
	let end = feature.geometry.coordinates[len-1];
	let startindex = coord2str(start);
	let endindex = coord2str(end);
	let startid,endid;
	if(vertices[startindex]!==undefined){
		startid=vertices[startindex]
	}else{
		vertices[startindex]=vertexid;
		startid=vertexid;
		vertexid++;
	}
	if(vertices[endindex]!==undefined){
		endid=vertices[endindex]
	}else{
		vertices[endindex]=vertexid;
		endid=vertexid;
		vertexid++;
	}
	cyelements.push({
		data: {
		  id: startid+'_'+endid,
		  source: startid,
		  target: endid,
		  coordinates:feature.geometry.coordinates,
		  length:feature.properties.SHAPE_Leng?feature.properties.SHAPE_Leng:length(feature.geometry.coordinates)
		}
	});
});
// console.log(vertices);
for(let i in vertices){
	let coordstr = i.split(',');
	let coords = coordstr.map(item=>parseFloat(item));
	cyelements.push({
		data: {
			id: vertices[i],
			coordinates:coords
		}
	});
}

fs.writeFileSync(outputfilename,JSON.stringify(cyelements));
console.log('done');

function coord2str(coord,hprecision=0.000001,vprecision=0.1){
	let lon = Math.floor(coord[0]/hprecision)*hprecision;
	let lat = Math.floor(coord[1]/hprecision)*hprecision;
	let height = Math.floor(coord[2]/vprecision)*vprecision;
	return lon.toFixed(6)+','+lat.toFixed(6)+','+height;
	// return coord[0].toFixed(6)+','+coord[1].toFixed(6)+','+height;
}

function length(coordinates){
	let sum = 0;
	for(let i=0;i<coordinates.length-1;i++){
		let position1 = Cesium.Cartesian3.fromDegrees(coordinates[i][0],coordinates[i][1],coordinates[i][2]);
		let position2 = Cesium.Cartesian3.fromDegrees(coordinates[i+1][0],coordinates[i+1][1],coordinates[i+1][2]);
		sum+=Cesium.Cartesian3.distance(position1,position2);
	}
	return sum;
}
